const http = require("http")
const fs = require("fs")
const path = require("path")
const url = require("url")

function mergeConfig(config) {
	return {
		port: 5000,
		dir: process.cwd(),
		...config,
	}
}

class Server {
	constructor(config) {
		this.config = mergeConfig(config)
	}
	start() {
		let server = http.createServer(this.serverHandle.bind(this))
		server.listen(this.config.port, () => {
			console.log("server is running at " + this.config.port)
		})
	}
	serverHandle(req, res) {
		let { pathname } = url.parse(req.url)
		pathname = decodeURIComponent(pathname)
		const absPath = path.join(this.config.dir, pathname)
		console.log("absPath: ", absPath)
		try {
			const stats = fs.statSync(absPath)
			if (stats.isFile()) {
				this.fileHandle(req, res, absPath)
			} else if (stats.isDirectory()) {
				this.directorHandle(req, res, absPath)
			}
		} catch (error) {
			this.errorHandle(req, res, error)
		}
	}
	errorHandle(req, res, error) {
		console.log("error: ", error)
		res.statusCode = 404
		res.setHeader("Content-type", "text/html;charset=utf-8")
		res.end("Not Found")
	}
	fileHandle(req, res, absPath) {
		res.setHeader('Content-type', 'text/html;charset=utf-8')
		const htmlString = fs.readFileSync(absPath)
		res.end(htmlString)
	}
	directorHandle(req, res, absPath) {
		// 如果是目录，默认访问目录下的 index.html 
		try {
			const curPath = path.join(absPath, 'index.html')
			console.log('curPath: ', curPath);
			const stats = fs.statSync(curPath)
			if(stats && stats.isFile()){
				res.setHeader('Content-type', 'text/html;charset=utf-8')
				const htmlString = fs.readFileSync(curPath)
				res.end(htmlString)
			}
		} catch (error) {
				this.errorHandle(req, res, error)
		}
	}
}

module.exports = Server
